package com.nantian.service.service.impl;

import com.nantian.esdao.UserEsDao;
import com.nantian.mongdao.UserMongoDao;
import com.nantian.entity.User;
import com.nantian.service.UserService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMongoDao userMongoDao;

    @Autowired
    private UserEsDao userEsDao;

    ////添加数据
    @Override
    public void save(User user) {
         userMongoDao.save(user);
    }

    //根据条件进行分页查询
    @Override
    public Page<User> searchUser(Integer pageNumber, Integer pageSize, String searchContent) {
        // 分页参数
        Pageable pageable = new PageRequest(pageNumber, pageSize);
        if("".equals(searchContent)||searchContent==null){
            //分页
            SearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withPageable(pageable).build();
            //查询
            Page<User> search = userEsDao.search(searchQuery);
            return search;
        }else {
            // 根据关键字进行查询
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(QueryBuilders.boolQuery()
                    .should(QueryBuilders.matchQuery("name", searchContent))
                    .should(QueryBuilders.matchQuery("address", searchContent)));
            // 分数、分页
            SearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withPageable(pageable)
                    .withQuery(functionScoreQueryBuilder).build();

            Page<User> searchPageResults = userEsDao.search(searchQuery);
            return searchPageResults;
        }
    }

}
